package com.atguigu.gmall.activity.listener;


import com.atguigu.gmall.activity.mapper.SeckillGoodsMapper;
import com.atguigu.gmall.activity.redis.CacheHelper;
import com.atguigu.gmall.activity.service.ActivityService;
import com.atguigu.gmall.activity.util.DateUtil;
import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.result.ResultCodeEnum;
import com.atguigu.gmall.constant.MqConst;
import com.atguigu.gmall.model.activity.SeckillGoods;
import com.atguigu.gmall.model.activity.UserRecode;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;

@Component
public class ActivityListener {


    @Autowired
    private ActivityService activityService;
    @Autowired
    private SeckillGoodsMapper seckillGoodsMapper;

    @Autowired
    private RedisTemplate redisTemplate;
    //接收
    @RabbitListener(bindings = @QueueBinding(
        value = @Queue(value = MqConst.QUEUE_TASK_1),
            exchange = @Exchange(value = MqConst.EXCHANGE_DIRECT_TASK),
            key = MqConst.ROUTING_TASK_1
    ))
    public void init(){
        //0:查询秒杀商品集合
        QueryWrapper<SeckillGoods> queryWrapper = new QueryWrapper<>();
        // 当天
        queryWrapper.eq("DATE_FORMAT(start_time,'%Y-%m-%d')",
                DateUtil.formatDate(new Date()));
         // 审核通过
        queryWrapper.eq("status","1");
        //库存大于0  great than equ.  gte    less than equ. lte
        queryWrapper.gt("stock_count",0);
        List<SeckillGoods> seckillGoodsList = seckillGoodsMapper.selectList(queryWrapper);

        //1)Redis   K:skuId V:秒杀对象  类型：Hash
        if(!CollectionUtils.isEmpty(seckillGoodsList)){
            for (SeckillGoods seckillGoods : seckillGoodsList) {
                if(!redisTemplate.opsForHash().hasKey(
                        RedisConst.SECKILL_GOODS,seckillGoods.getSkuId().toString())){

                    //一个一个放到Hash中
                    redisTemplate.opsForHash().put(RedisConst.SECKILL_GOODS,
                            seckillGoods.getSkuId().toString(),seckillGoods);
                    //2)防超卖   List
                    String[] ids = parseCount(
                            seckillGoods.getSkuId().toString(),
                            seckillGoods.getStockCount());
                    redisTemplate.opsForList().leftPushAll("list:" +
                            seckillGoods.getSkuId().toString(),ids);
                    //3:状态位  发布、订阅模式
                    redisTemplate.convertAndSend("seckillpush",
                            seckillGoods.getSkuId() + ":1");

                }
            }

        }
    }

    private String[] parseCount(String id, Integer stockCount) {

        String[] ids = new String[stockCount];
        for (Integer i = 0; i < stockCount; i++) {
            ids[i] = id;
        }
        return ids;
    }

    //接收开始抢购上半场 排队
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.QUEUE_SECKILL_USER),
            exchange = @Exchange(value = MqConst.EXCHANGE_DIRECT_SECKILL_USER),
            key = MqConst.ROUTING_SECKILL_USER
    ))
    public void queue123(UserRecode userRecode){
        ////        1、校验限购
        Boolean isNotBuy = redisTemplate.opsForValue().setIfAbsent(
                RedisConst.SECKILL_USER + userRecode.getUserId() + ":"
                        + userRecode.getSkuId(), "");
        if(!isNotBuy){
            //此用户你已经买过了
            return;
        }
//        2、判断状态位  skuId:1（本）
        String state = (String) CacheHelper.get(userRecode.getSkuId().toString());
        if(!"1".equals(state)){
           //无货
            return;
        }

//        3、是否有库存（修改状态位）
        Object o = redisTemplate.opsForList().rightPop("list:" +
                userRecode.getSkuId().toString());
        if(null == o){
            //已售完  修改状态位
            redisTemplate.convertAndSend("seckillpush",
                    userRecode.getSkuId() + ":0");
            return;
        }
//        4、获取抢购资格
        redisTemplate.opsForHash().put(
                RedisConst.SECKILL_ORDERS + userRecode.getUserId(),
                userRecode.getSkuId().toString(),userRecode.getSkuId());
//        5、后续....
    }

}
